package test5.lupeng.jf.com.teamdemo.activitys;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sendtion.xrichtext.RichTextEditor;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import test5.lupeng.jf.com.teamdemo.R;
import test5.lupeng.jf.com.teamdemo.bean.request.BlogBean;
import test5.lupeng.jf.com.teamdemo.bean.response.ImageResponse;
import test5.lupeng.jf.com.teamdemo.untils.HTTPUtils;


public class WriteBlogActivity extends AppCompatActivity {
    private static final String TAG = "WriteBlogActivity";
    private String userId;
    private final int IMAGE_CODE = 0;
    private RichTextEditor et_new_content;

    ArrayList<String> content = new ArrayList<>();
    private int blogType;
    private String title;
    int current = 0;
    private List<RichTextEditor.EditData> editList;
    Uri outputFileUri;


    public final static int CAMERA_REQUEST_CODE = 3;
    public static String SAVED_IMAGE_DIR_PATH = Environment.getExternalStorageDirectory().getPath() + "/AppName/camera/";// 拍照路径
    String cameraPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_blog);
        blogType = getIntent().getIntExtra("tag", 0);
        SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE);
        userId = sp.getString("objectId", null);
        initView();
    }

    private void initView() {

        ImageView iv_camera = (ImageView) findViewById(R.id.iv_camera);
        iv_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                File file = FileUtils.createImageFile();
                outputFileUri = Uri.fromFile(file);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(intent, 814);
                }
            }


        });

        ImageView iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        switch (blogType) {
            case 1:
                tv_title.setText("杂谈");
                break;
            case 2:
                tv_title.setText("提问");
                break;
            case 3:
                tv_title.setText("分享");
                break;
        }
        et_new_content = (RichTextEditor) findViewById(R.id.et_new_content);

        ImageView iv_image = (ImageView) findViewById(R.id.iv_image);
        iv_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent getAlbum = new Intent(Intent.ACTION_PICK);
                getAlbum.setType("image/*");
                startActivityForResult(getAlbum, IMAGE_CODE);
            }
        });


        final EditText edit = (EditText) findViewById(R.id.edit);


        TextView tv_publish = (TextView) findViewById(R.id.tv_publish);
        tv_publish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                title = edit.getText().toString();
                getEditData();

            }
        });
    }


    private void publishImages(String picturePath) {

        String type;
        if (picturePath.endsWith(".png")) {
            type = ".png";
        } else if (picturePath.endsWith(".jpg")) {
            type = ".jpg";
        } else {
            type = ".jpeg";
        }
        OkHttpClient okHttpClient = new OkHttpClient();
        MediaType IMAGETYPE = MediaType.parse("image/*");
        File imagePath = new File(picturePath);
        RequestBody body = RequestBody.create(IMAGETYPE, imagePath);
        Log.e(TAG, "publishImages: " + picturePath);
        Request request = new Request.Builder()
                .post(body)
                .addHeader("X-LC-Id", "S5KdTtqGDUwpImMvQ6HAJYaL-gzGzoHsz")
                .addHeader("X-LC-Key", "NRPgCGiGxjbtGN2Bn0mlglrL")
                .addHeader("Content-Type", "image/jpeg")
                .url("https://leancloud.cn:443/1.1/files/" + System.currentTimeMillis() + type)
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonResult = response.body().string();
                Log.e(TAG, "onResponse: " + response.code());
                if (response.code() == 201) {
                    ImageResponse bean = new Gson().fromJson(jsonResult, ImageResponse.class);
                    content.add(bean.getUrl());
                    Log.e(TAG, "content " + content.toString());
                    if (current == editList.size()) {
                        publishBlog(userId, title, blogType, content);
                    }
                }
            }
        });

    }


    private void publishBlog(String userId, String title, int blogType, ArrayList<String> contentArr) {
        Log.e(TAG, "publishBlog: " + contentArr.toString());
        if (userId == null || "".equals(userId)) {
            Toast.makeText(this, "用户id为空，请登录后再发表博客！", Toast.LENGTH_SHORT).show();
        }
        String url = "https://leancloud.cn:443/1.1/functions/issueBlog";
        BlogBean bean = new BlogBean(userId, title, blogType, contentArr);
        Request request = HTTPUtils.requestPost(bean, url);
        OkHttpClient client = new OkHttpClient();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                String jsonResult = response.body().string();
                Log.e(TAG, "onResponse: " + jsonResult);
                Log.e(TAG, "onResponse: " + response.code());
                if (response.code() == 200) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(WriteBlogActivity.this, "发布成功！", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    });
                    return;
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case IMAGE_CODE:
                //TODO
                //获取用户选择的图片
                if (resultCode == RESULT_OK) {
                    ContentResolver resolver = getContentResolver();
                    Bitmap bitmap = null;
                    Uri uri = data.getData();
                    try {
                        //获取图片路径
                        uri = data.getData(); //获取系统返回的照片的Uri
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        Cursor cursor = getContentResolver().query(uri,
                                filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                        cursor.moveToFirst();
                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        //获取照片路径
                        String mPicturePath = cursor.getString(columnIndex);
                        cursor.close();
                        Log.i(TAG, "onActivityResult: " + mPicturePath);


                        //显示图片
                        bitmap = MediaStore.Images.Media.getBitmap(resolver, uri);
                        et_new_content.insertImage(bitmap, mPicturePath);


                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;


            case 814:
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), outputFileUri);
                    et_new_content.insertImage(bitmap,outputFileUri.getPath());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                break;
        }
    }


    private void getEditData() {
        Toast.makeText(this, "发布中", Toast.LENGTH_SHORT).show();
        ArrayList<String> imagePathArr = new ArrayList<>();
        editList = et_new_content.buildEditData();
        for (RichTextEditor.EditData itemData : editList) {
            if (itemData.inputStr != null) {
                content.add(itemData.inputStr);
            } else if (itemData.imagePath != null) {
                publishImages(itemData.imagePath);
            }
            current++;
        }


        Log.e(TAG, "getEditData: " + content.toString());


    }

    public static class FileUtils {
        public static File createImageFile() {
            // Create an image file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = "JPEG_" + timeStamp + "_";
            try {
                File imageFile = File.createTempFile(imageFileName,  /* prefix */
                        ".jpg",         /* suffix */
                        Environment.getExternalStorageDirectory()      /* directory */);
                return imageFile;
            } catch (IOException e) {
                //do noting
                return null;
            }
        }
    }

}
